<template>
  <div class="messages">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名" 
            clearable 
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.isReplied" 
            placeholder="请选择状态" 
            clearable
            @change="handleSearch"
          >
            <el-option label="未回复" :value="false" />
            <el-option label="已回复" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item label="留言时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 留言列表 -->
    <el-table
      v-loading="loading"
      :data="messageList"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="content" label="留言内容" min-width="300" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isReplied ? 'success' : 'warning'">
            {{ row.isReplied ? '已回复' : '未回复' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="留言时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleReply(row)">回复</el-button>
          <el-button
            type="danger"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复留言"
      width="600px"
    >
      <div v-if="currentMessage" class="message-details">
        <div class="message-content">
          <div class="message-header">
            <span class="username">{{ currentMessage.username }}</span>
            <span class="time">{{ formatDate(currentMessage.createTime) }}</span>
          </div>
          <div class="content">{{ currentMessage.content }}</div>
        </div>
        <el-form
          ref="replyFormRef"
          :model="replyForm"
          :rules="replyRules"
          label-width="80px"
          class="reply-form"
        >
          <el-form-item label="回复内容" prop="reply">
            <el-input
              v-model="replyForm.reply"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReplySubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMessageList,
  replyMessage,
  deleteMessage
} from '@/api/admin'
import { Search } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  username: '',
  isReplied: null,
  dateRange: []
})

// 留言列表数据
const loading = ref(false)
const messageList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 回复对话框
const replyDialogVisible = ref(false)
const currentMessage = ref(null)
const replyFormRef = ref(null)
const replyForm = reactive({
  messageId: '',
  reply: ''
})

// 回复表单验证规则
const replyRules = {
  reply: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ]
}

// 加载留言列表
const loadMessageList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      username: searchForm.username,
      isReplied: searchForm.isReplied
    }
    if (searchForm.dateRange?.length === 2) {
      params.startTime = searchForm.dateRange[0]
      params.endTime = searchForm.dateRange[1]
    }
    const res = await getMessageList(params)
    if (res.code === 200) {
      messageList.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '加载留言列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('加载留言列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadMessageList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : null
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadMessageList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadMessageList()
}

// 回复留言
const handleReply = (row) => {
  currentMessage.value = row
  replyForm.messageId = row.id
  replyForm.reply = row.reply || ''
  replyDialogVisible.value = true
}

// 提交回复
const handleReplySubmit = async () => {
  if (!replyFormRef.value) return
  await replyFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await replyMessage(replyForm.messageId, replyForm.reply)
        ElMessage.success('回复成功')
        replyDialogVisible.value = false
        loadMessageList()
      } catch (error) {
        console.error(error)
        ElMessage.error('回复失败')
      }
    }
  })
}

// 删除留言
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该留言吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMessage(row.id)
      ElMessage.success('删除成功')
      loadMessageList()
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 工具函数
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 监听状态变化
watch(() => searchForm.isReplied, () => {
  currentPage.value = 1
  loadMessageList()
})

onMounted(() => {
  loadMessageList()
})
</script>

<style scoped>
.messages {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.message-details {
  padding: 20px;
}

.message-content {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.username {
  font-weight: bold;
  color: #303133;
}

.time {
  color: #909399;
  font-size: 14px;
}

.content {
  color: #606266;
  line-height: 1.6;
}

.reply-form {
  margin-top: 20px;
}
</style> 